package demo;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2024-01-24  18:49
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    /**
     *对数组进行初始化
     * @param array
     */
    public void initElem(int[] array) {
        for(int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            this.usedSize++;
        }
    }

    /**
     * 创建大根堆
     */
    public void createHeap() {
        for(int parent = (usedSize-1-1) / 2; parent >= 0; parent--) {
             siftDown(parent, usedSize);
        }
    }

    private void siftDown(int parent, int len) {
        int child = 2 * parent + 1;

        while(child < len) {
            if(child + 1 < len && elem[child] < elem[child + 1]) {
                child = child + 1;
            }
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    public void push(int val) {
        //满
        if(isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        //未满
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child) {
        int parent = (child -1) / 2;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int pop() {
        int oldVal = elem[0];
        swap(0,usedSize - 1);
        usedSize--;
        siftDown(0,usedSize);
        return oldVal;
    }

    private boolean isEmpty() {
        return usedSize == 0;
    }

    private boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     ** swap交换
     */
    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }
}
